from django.db import models
from django.contrib.auth.hashers import make_password, check_password
# 重写
# PermissionsMixin 权限相关
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, AbstractUser, BaseUserManager


class UserManager(BaseUserManager):
    """
    用来创建用户
        炒鸡管理员
        普通用户
    用户是通过手机号注册的
    """
    def _create_user(self, telephone, username, password, **extra_fields):
        # self.model ===> User
        print(extra_fields)
        user = self.model(telephone=telephone, username=username, **extra_fields)
        # 把明文密码加密
        user.set_password(password)
        user.save()
        return user

    # 这个方法 创建用户 并不是创建超级用户
    def create_user(self, telephone, username, password, **extra_fields):
        extra_fields["is_superuser"] = False
        extra_fields["is_staff"] = False
        return self._create_user(telephone=telephone, username=username, password=password, **extra_fields)

    # 创建炒鸡用户
    def create_superuser(self, telephone, username, password, **extra_fields):
        extra_fields["is_superuser"] = True
        extra_fields["is_staff"] = True
        return self._create_user(telephone=telephone, username=username, password=password, **extra_fields)

# python manage createsuperuser  ==> 调用自己重写的方法
# 自己定义的 重写自带 User
class User(AbstractBaseUser, PermissionsMixin):
    telephone = models.CharField(max_length=11, unique=True)
    username = models.CharField(max_length=30)
    email = models.EmailField(unique=True, null=True)
    # 用户是否可用
    is_active = models.BooleanField(default=True)
    join_date = models.DateTimeField(auto_now_add=True)
    # 1 = 保密  2 = 男  3 => 女
    gender = models.IntegerField(default=1)
    # true 表示是公司的员工 0
    is_staff = models.BooleanField(null=True)
    # django 自带的验证
    # user = authenticate(username=telephone, password=password)
    USERNAME_FIELD = 'telephone'
    # 以后发动邮件的时候 会使用 email
    EMAIL_FIELD = 'email'
    # 当我们在python manage.py createsuperuser ==>  email  password
    # python manage.py createsuperuser  1.USERNAME_FIELD=telephone  2.username  3.password
    REQUIRED_FIELDS = ['username']

    #  User.objects.all() ==> 所有的用户
    objects = UserManager()

